package com.liws.hellojuc.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ：liweisheng
 * @date ：2022/1/31 6:58
 * @description：reentrantLock的公平锁机制例子：
 */
public class ReentrantLockTest02 {

    /**
     * 公平锁：线程A、B、C、D、E依次获取锁
     * 非公平锁：线程A、B、C、D、E乱序获取锁
     */
    private static final Lock lock=new ReentrantLock(true);

    public static void main(String[] args) {
        new Thread(()->test(),"线程A").start();
        new Thread(()->test(),"线程B").start();
        new Thread(()->test(),"线程C").start();
        new Thread(()->test(),"线程D").start();
        new Thread(()->test(),"线程E").start();

    }

    public static void  test(){
        for (int i=0;i<2;i++) {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "获取了锁");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(Thread.currentThread().getName() + "释放了锁");
                lock.unlock();

            }
        }
    }

}
